#!/usr/bin/python
import xmpp

class Client:
    def __init__(self, client, jid, password, server):
        self.client = client
        self.password = password
        self.jid = jid
        self.server = server
        self.buffered_messages = []
        self.show = 1

    def register_handlers(self):
        self.client.RegisterHandler('message', self.xmpp_message)

    def xmpp_message(self, con, event):
        type = event.getType()
        fromjid = event.getFrom().getStripped().split('@')[0]
        composing = event.getTags('composing')
        paused = event.getTags('paused')
        if self.show:
            if composing:
                print "%s is typing" % fromjid
            if paused:
                print "%s stopped typing" % fromjid
        if type in ['message', 'chat', None]:
            if event.getBody():
                message = u"%s" % fromjid + u" => " + event.getBody()
                if not self.show:
                    self.buffered_messages.append(message)
                else:
                    print message

    def show_buffered_messages(self):
        for message in self.buffered_messages:
            print message
        self.buffered_messages = []

    def stdio_message(self, message, jid):
        m = xmpp.protocol.Message(to=jid, body=message, typ='chat')
        self.client.send(m)

    def xmpp_connect(self):
        con = self.client.connect(self.server)
        if not con:
            sys.stderr.write('could not connect!\n')
            return False
        auth = self.client.auth(self.jid.getNode(), self.password,
                                resource=self.jid.getResource())
        if not auth:
            sys.stderr.write('could not authenticate!\n')
            return False
        self.register_handlers()
        return con

